package com.xxgc.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 订单的消息队列配置
 */
@Configuration
public class RabbitOrderConfig {

    //交换机的名称
    private final String EXCHANGE_NAME = "order_exchange";
    //队列的名称
    private final String QUEUE_NAME = "order_queue";
    //死信交换机的名称
    private final String DEAD_EXCHANGE_NAME = "dead_order_exchange";
    //死信队列的名称
    private final String DEAD_QUEUE_NAME = "dead_order_queue";

    /**
     * 创建交换机
     * @return
     */
    @Bean("iocOrderExchange")
    public Exchange getExchange(){
        return ExchangeBuilder
                .topicExchange(EXCHANGE_NAME)
                //是否持久化
                .durable(true)
                .build();
    }

    /**
     * 创建队列
     * @return
     */
    @Bean("iocOrderQueue")
    public Queue getMessageQueue(){
        return QueueBuilder
                .durable(QUEUE_NAME)
                .ttl(20000)//在普通交换机中最大停留时间
                .deadLetterExchange(DEAD_EXCHANGE_NAME)//死信交换机的名称
                .deadLetterRoutingKey("order_dead")//死信路由关键字
                .build();
    }

    /**
     * 创建死信交换机
     * @return
     */
    @Bean("iocDeadExchange")
    public Exchange getDeadExchange(){
        return ExchangeBuilder
                .topicExchange(DEAD_EXCHANGE_NAME)
                //是否持久化
                .durable(true)
                .build();
    }

    /**
     * 创建死信队列
     * @return
     */
    @Bean("iocDeadQueue")
    public Queue getDeadMessageQueue(){
        return QueueBuilder
                .durable(DEAD_QUEUE_NAME)
                .build();
    }

    /**
     * 绑定交换机和队列
     * @param exchange
     * @param queue
     * @return
     */
    @Bean
    public Binding bindingOrderExchangeQueue(
            @Qualifier("iocOrderExchange") Exchange exchange,
            @Qualifier("iocOrderQueue") Queue queue
    ){
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("#.order.#")
                .noargs();
    }

    /**
     * 绑定死信交换机和死信队列
     * @param exchange
     * @param queue
     * @return
     */
    @Bean
    public Binding bindingDeadExchangeQueue(
            @Qualifier("iocDeadExchange") Exchange exchange,
            @Qualifier("iocDeadQueue") Queue queue
    ){
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("#.order_dead.#")
                .noargs();
    }

}
